<?php

namespace  app\service;


//use app\model\PartnerModel;
use app\model\PartnerUserModel;
use app\utils\Md5Service;

Class MemberService{
    public static  function login($param)
    {

        $partnerInfo= PartnerUserModel::GetPartnerUserInfo($param);
         if (empty($partnerInfo)){
            returnFail(21013,'信息错误');
        }
        $redis=linkRedis(5);
        $errCount=$redis->get($param['mobile']."_login_errcount");
        if ($errCount>=5){
             returnFail(20001,'密码登录错误过多,1个小时之后解封！');
        }
          if (Md5Service::encryptMd5($param['password'],$partnerInfo['salt'])!=$partnerInfo['password']){
              if (!empty($errCount)){
                  $redis->incr($param['mobile']."_login_errcount");
              }else{
                  $redis->set($param['mobile']."_login_errcount",1,3600);
              }

            returnFail(21014,'账号或者密码错误');
        }
        if ($partnerInfo['status']==2){
            returnFail(21015,'账号已禁用,请联系管理员处理');
        }
        $newApiSalt=GetRandStr(10);
         //更新登录信息
        $addRes=PartnerUserModel::UpdatePartnerUserLoginInfo($partnerInfo,$param,$newApiSalt,$param['login_channel']);
        if ($addRes==false){
            returnFail(21016,'系统内部错误,请联系管理员处理');
        }
        unset($partnerInfo['password']);
        unset($partnerInfo['salt']);
        //生成token
        $token=geterateToken();
        $redisLink=linkRedis(6);
        $partnerInfo['token']=$token;
        // 1 tms 2 wms 3 oms
        if ($param['login_channel']==1){
            $partnerInfo['api_salt']=$newApiSalt;
            $token_id='partner_token_'.$partnerInfo['id'];
        }elseif ($param['login_channel']==2){
            $partnerInfo['wms_api_salt_h5']=$newApiSalt;
            $token_id='partner_wmstoken_'.$partnerInfo['id'];
        }
        $redisLink->set('partner_user_'.$partnerInfo['id'],json_encode($partnerInfo));
        $redisLink->set($token_id,json_encode(['token'=>$token,'expiretime'=>time()+259200]),259000);

        return $partnerInfo;
    }

    public static  function  getPartnerIdByUid($uid=0){
       return  PartnerUserModel::getPartnerIdByUid($uid);
    }

    public static function getCompanyIdByUid($uid = 0)
    {
        return PartnerUserModel::getCompanyIdByUid($uid);
    }

}